<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="检验模板编码" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="quality_template" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="检验模板名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="检验类型" prop="typeCode">
          <DictSelect
            :band-value.sync="formData.typeCode"
            dict-type="checkoutType"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item v-if="isShow" label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div class="formItem_header">
        检验信息
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item" @click="importSpareParts">
            <svg-icon icon-class="导入" />
            <div class="item_name">导入</div>
          </a>
          <a v-if="formData.id" class="formItem_header_operate_item" @click="getExportData">
            <svg-icon icon-class="导出" />
            <div class="item_name">导出</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="removeRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container" class="table_container addRow_table draggableTable">
        <el-table
          ref="table"
          :data="tableData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
          :cell-class-name="cellClassName"
          :header-cell-class-name="headerCellClassName"
          :row-class-name="rowClassName"
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column
            prop="rankId"
            label="序号"
            width="80"
          >
            <template slot-scope="scope">
              <div v-if="!scope.row.isAdd">{{ scope.row.rankId }}</div>
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="qualityItemName"
            label="检验项目"
          >
            <template slot-scope="scope">
              <div v-if="!scope.row.isAdd">{{ scope.row.qualityItemName }}</div>
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="itemProperty"
            label="项目属性"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.itemProperty" placeholder="请选择">
                <el-option
                  v-for="item in itemPropertyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="itemDimension"
            label="项目维度"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.itemDimension" placeholder="请选择">
                <el-option
                  v-for="item in itemDimensionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="qualityCheckType"
            label="质检方式"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.qualityCheckType" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="qualityCheckTool"
            label="检验工具"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.qualityCheckTool" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
          <el-table-column
            prop="qualityCheckStandard"
            label="检验标准"
          >
            <template slot-scope="scope">
              <el-input v-if="!scope.row.isAdd" v-model="scope.row.qualityCheckStandard" placeholder="请输入" />
              <div v-else />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="main_bottom">
      <!-- <div>进度{{ progressTitle }}</div> -->
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, importCheckout } from '@/api/qualityManage/checkoutTemplate'
import Sortable from 'sortablejs'
import ImportData from '@/components/JLink/common/ImportData'
import { export2Excel } from '@/utils/util'
import addOrCheckoutProject from '../checkoutProject/addCheckoutProject'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {}
  },
  data() {
    return {
      loading: true,
      isShow: false,
      formData: {
        code: undefined,
        name: undefined,
        remark: undefined,
        typeLabel: undefined,
        typeCode: undefined,
        fileUrl: '',
        fileName: '',
        fileRealName: '',
        status: '1'
      },
      itemPropertyOptions: [
        { value: '0', label: '判定项' },
        { value: '1', label: '记录项' }
      ],
      itemDimensionOptions: [
        { value: '0', label: '整体项目' },
        { value: '1', label: '个体项目' }
      ],
      rules: {
        code: [
          { required: true, message: '检验模板编码不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '检验模板名称不能为空', trigger: 'change' }
        ],
        typeCode: [
          { required: true, message: '检验类型不能为空', trigger: 'change' }
        ]
      },
      tableColumn: [
        { prop: 'qualityItemName', label: '检验项目' },
        { prop: 'itemPropertyName', label: '项目属性' },
        { prop: 'itemDimensionName', label: '项目维度' },
        { prop: 'qualityCheckType', label: '质检方式' },
        { prop: 'qualityCheckTool', label: '检验工具' },
        { prop: 'qualityCheckStandard', label: '检验标准' }
      ],
      progressTitle: '',
      tableHeight: '400',
      pageId: '检验模板检验信息',
      selectionsAll1: [],
      tableData: [
      ]
    }
  },
  mounted() {
    if (!this.id) { // 没有id就是新增
      this.loading = false
    } else { // 有id就是编辑
      this.formData.id = this.id
      this.getById()
      setTimeout(() => {
        this.rowDrop()
      }, 50)
    }
  },
  methods: {// 表格拖动排序
    headerCellClassName(data) {
      if (['itemProperty', 'itemDimension'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    setFileName(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.draggableTable')
        .querySelector('.el-table__body-wrapper').querySelector('tbody')
      const _this = this
      Sortable.create(tbody, {
        draggable: '.normalRow',
        filter: '.el-input__inner', // Selectors that do not lead to dragging (String or Function)
        preventOnFilter: false, // Call `event.preventDefault()` when triggered `filter`
        onEnd({ newIndex, oldIndex }) {
          const cacheData1 = _this.$deepClone(_this.tableData[oldIndex])
          const cacheData2 = _this.$deepClone(_this.tableData[newIndex])
          const cacheTableData = _this.$deepClone(_this.tableData)
          cacheTableData[newIndex] = cacheData1
          cacheTableData[oldIndex] = cacheData2
          _this.reSortTable(cacheTableData)
        }
      })
    },
    getExportData() {
      export2Excel(this.tableColumn, this.tableData, this.pageId)
    },
    reSortTable(tableData) { // 对表格重新排序
      tableData.forEach((item, index) => {
        if (!item.isAdd) {
          item.rankId = index + 1
        }
      })
      this.tableData = []
      setTimeout(() => { // 加延时重置表格
        this.tableData = tableData
      }, 50)
    },
    importSpareParts() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importCheckout(files, (ps) => {
        this.progressTitle = Math.floor((ps.loaded / ps.total) * 100)
        console.log(ps)
        console.log(this.progressTitle)
      }).then(res => {
        if (res.data) {
          this.tableData = []
          console.log(this.progressTitle)
          res.data.forEach(item => {
            // item.batchInventoryId = item.batchId
            this.tableData.push(item)
          })
        }
      })
    },
    addRow() {
      const cacheTableData = this.$deepClone(this.tableData)
      cacheTableData.forEach(item => {
        item.id = item.qualityItemId
        delete item['qualityItemId']
      })
      this.$layer.iframe({
        // 弹框
        content: {
          content: addOrCheckoutProject, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: cacheTableData
          } // props
        },
        area: ['880px', '700px'],
        title: '选择检验项目', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
      setTimeout(() => {
        this.rowDrop()
      }, 50)
    },
    removeRow(row) {
      if (this.selectionsAll1.length > 0) {
        this.selectionsAll1.forEach(item => {
          this.tableData.splice(this.tableData.indexOf(item), 1)
        })
        this.reSortTable(this.tableData)
      }
    },
    cellClassName(data) {
      // if (data.column.property == 'operate') {
      //   if (data.rowIndex % 2 == 0) { // 单数行
      //     return 'fixed one'
      //   } else { // 双数行
      //     return 'fixed two'
      //   }
      // }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length - 1 && row.isAdd) {
        return 'addRow'
      } else {
        return 'normalRow'
      }
    },
    getById() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.tableData = res.data.data
        this.isShow = true
        this.loading = false
        // this.tableData.push({ isAdd: true })
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const tableData = JSON.parse(JSON.stringify(this.tableData))
          if (tableData.length == 0) {
            this.$message.warning('请添加检验信息')
            return false
          }
          if (tableData && tableData.length > 0) {
            if (tableData.filter(item => !item.itemProperty).length > 0) {
              this.$message.warning('项目属性不能为空')
              return false
            }
          }
          if (tableData && tableData.length > 0) {
            if (tableData.filter(item => !item.itemDimension).length > 0) {
              this.$message.warning('项目维度不能为空')
              return false
            }
          }
          this.formData.data = tableData
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getList() // 调用父组件的刷新方法
          })
        }
      })
    },
    // 选择项目回调
    showMaterial(data) {
      const cacheTableData = []
      data.forEach((item, index) => {
        if (this.tableData.filter(item2 => item2.qualityItemId == item.id).length == 1) {
          const row = this.tableData.filter(item2 => item2.qualityItemId == item.id)[0]
          row.rankId = index + 1
          cacheTableData.push(row)
        } else {
          const row2 =
            {
              rankId: index + 1,
              qualityItemName: item.name,
              qualityItemId: item.id
            }
          cacheTableData.push(row2)
        }
      })
      this.tableData = cacheTableData
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
</style>
